package com.stx.jeepay.manager.controller;

import cn.hutool.core.codec.Base64;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.stx.jeepay.core.aop.MethodLog;
import com.stx.jeepay.core.entity.SysUserEntity;
import com.stx.jeepay.core.enums.CS;
import com.stx.jeepay.core.expection.BizException;
import com.stx.jeepay.core.model.ApiPageRes;
import com.stx.jeepay.core.model.ApiRes;
import com.stx.jeepay.core.service.SysUserAuthService;
import com.stx.jeepay.core.service.SysUserService;
import com.stx.jeepay.manager.service.AuthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@Api(tags = "系统管理（操作员）")
@RestController
@RequestMapping("api/sysUsers")
public class SysUserController extends CommonCtrl {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserAuthService sysUserAuthService;
    @Autowired
    private AuthService authService;

    @ApiOperation("操作员列表（分页接口）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "pageNumber", value = "分页页码", dataType = "int", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "分页条数", dataType = "int", defaultValue = "20"),
            @ApiImplicitParam(name = "sysUserId", value = "用户ID"),
            @ApiImplicitParam(name = "realname", value = "用户姓名")
    })
    @PreAuthorize("hasAuthority( 'ENT_UR_USER_LIST' )")
    @GetMapping("")
    public ApiPageRes<SysUserEntity> list() {
        SysUserEntity queryObject = getObject(SysUserEntity.class);

        LambdaQueryWrapper<SysUserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserEntity::getSysType, CS.SYS_TYPE.MGR);

        if (StringUtils.isNotEmpty(queryObject.getRealname())) {
            queryWrapper.like(SysUserEntity::getRealname, queryObject.getRealname());
        }

        if (queryObject.getSysUserId() != null) {
            queryWrapper.eq(SysUserEntity::getSysUserId, queryObject.getSysUserId());
        }
        queryWrapper.orderByDesc(SysUserEntity::getCreatedAt);

        IPage<SysUserEntity> pages = sysUserService.page(getIPage(), queryWrapper);

        return ApiPageRes.pages(pages);
    }

    @ApiOperation("操作员详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "recordId", value = "用户ID", required = true, dataType = "Long")
    })
    @PreAuthorize("hasAuthority( 'ENT_UR_USER_EDIT' )")
    @GetMapping("/{recordId}")
    public ApiRes detail(@PathVariable("recordId") Long recordId) {
        return ApiRes.ok(sysUserService.getById(recordId));
    }

    @ApiOperation("添加操作员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "isAdmin", value = "是否超管（超管拥有全部权限） 0-否 1-是", required = true, dataType = "Byte"),
            @ApiImplicitParam(name = "loginUsername", value = "登录用户名", required = true),
            @ApiImplicitParam(name = "realname", value = "真实姓名", required = true),
            @ApiImplicitParam(name = "sex", value = "性别 0-未知, 1-男, 2-女", required = true, dataType = "Byte"),
            @ApiImplicitParam(name = "telphone", value = "手机号", required = true),
            @ApiImplicitParam(name = "userNo", value = "员工编号", required = true),
            @ApiImplicitParam(name = "state", value = "状态: 0-停用, 1-启用", required = true, dataType = "Byte")
    })
    @PreAuthorize("hasAuthority( 'ENT_UR_USER_ADD' )")
    @MethodLog(remark = "添加操作员")
    @PostMapping("")
    public ApiRes add() {
        SysUserEntity sysUser = getObject(SysUserEntity.class);
        sysUser.setBelongInfoId("0");
        sysUserService.addSysUser(sysUser, CS.SYS_TYPE.MGR);
        return ApiRes.ok();
    }

    @ApiOperation("修改操作员信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "recordId", value = "用户ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "isAdmin", value = "是否超管（超管拥有全部权限） 0-否 1-是", required = true, dataType = "Byte"),
            @ApiImplicitParam(name = "loginUsername", value = "登录用户名", required = true),
            @ApiImplicitParam(name = "realname", value = "真实姓名", required = true),
            @ApiImplicitParam(name = "sex", value = "性别 0-未知, 1-男, 2-女", required = true, dataType = "Byte"),
            @ApiImplicitParam(name = "telphone", value = "手机号", required = true),
            @ApiImplicitParam(name = "userNo", value = "员工编号", required = true),
            @ApiImplicitParam(name = "state", value = "状态: 0-停用, 1-启用", required = true, dataType = "Byte"),
            @ApiImplicitParam(name = "resetPass", value = "是否重置密码", dataType = "Boolean"),
            @ApiImplicitParam(name = "confirmPwd", value = "待更新的密码，base64加密"),
            @ApiImplicitParam(name = "defaultPass", value = "是否默认密码", dataType = "Boolean")
    })
    @PreAuthorize("hasAuthority( 'ENT_UR_USER_EDIT' )")
    @MethodLog(remark = "修改操作员信息")
    @PutMapping("/{recordId}")
    public ApiRes update(@PathVariable("recordId") Long recordId) {
        SysUserEntity sysUser = getObject(SysUserEntity.class);
        sysUser.setSysUserId(recordId);
        //判断是否自己禁用自己
        if (recordId.equals(getCurrentUser().getSysUser().getSysUserId()) && sysUser.getState() != null && sysUser.getState() == CS.PUB_DISABLE) {
            throw new BizException("系统不允许禁用当前登陆用户！");
        }
        //判断是否重置密码
        Boolean resetPass = getReqParamJSON().getBoolean("resetPass");
        if (resetPass != null && resetPass) {
            String updatePwd = getReqParamJSON().getBoolean("defaultPass") == false ? Base64.decodeStr(getValStringRequired("confirmPwd")) : CS.DEFAULT_PWD;
            sysUserAuthService.resetAuthInfo(recordId, null, null, updatePwd, CS.SYS_TYPE.MGR);
            // 删除用户redis缓存信息
            authService.delAuthentication(Arrays.asList(recordId));
        }

        sysUserService.updateSysUser(sysUser);

        //如果用户被禁用，需要更新redis数据
        if (sysUser.getState() != null && sysUser.getState() == CS.PUB_DISABLE){
            authService.refAuthentication(Arrays.asList(recordId));
        }
        return ApiRes.ok();
    }

    @ApiOperation("删除操作员信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "recordId", value = "用户ID", required = true, dataType = "Long")
    })
    @PreAuthorize("hasAuthority( 'ENT_UR_USER_DELETE' )")
    @MethodLog(remark = "删除操作员信息")
    @DeleteMapping("/{recordId}")
    public ApiRes delete(@PathVariable("recordId") Long recordId){
        SysUserEntity sysUser = sysUserService.getById(recordId);
        if (sysUser==null){
            throw new BizException("该操作员不存在！");
        }

        //判断是否自己删除自己
        if (recordId.equals(getCurrentUser().getSysUser().getSysUserId())){
            throw new BizException("系统不允许删除当前登陆用户！");
        }

        // 删除用户
        sysUserService.removeUser(sysUser, CS.SYS_TYPE.MGR);

        //如果用户被删除，需要更新redis数据
        authService.refAuthentication(Arrays.asList(recordId));

        return ApiRes.ok();
    }
}
